package com.bete.otherutils;

import static android.content.Context.ACTIVITY_SERVICE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;

import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.util.List;

import me.jessyan.autosize.utils.LogUtils;


public abstract class BaseActivity extends AppCompatActivity  {
    private static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000;
    private ProgressDialog progressDialog;

    /**
     * 显示进度对话框
     */
    public void showProgressDialog(String text) {
        closeProgressDialog();
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
        }
        progressDialog.setMessage(text);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    public interface ProcessWaitingFlag {
        boolean isWaitingFlag();
    }

    public interface ProcessFinalHandle {
        void finalHandle();
    }

    public void showProgressDialog(String text, final ProcessWaitingFlag processWaitingFlag) {
        closeProgressDialog();
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
        }
        progressDialog.setMessage(text);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                while (processWaitingFlag.isWaitingFlag()) {
                    try {
                        sleep(100);
                    } catch (InterruptedException e) {
                    }
                }
                closeProgressDialog();
            }
        }.start();
    }

    public void showProgressDialog(String text, final ProcessWaitingFlag processWaitingFlag, final ProcessFinalHandle processFinalHandle) {
        closeProgressDialog();
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
        }
        progressDialog.setMessage(text);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                while (processWaitingFlag.isWaitingFlag()) {
                    try {
                        sleep(100);
                    } catch (InterruptedException e) {
                        LogUtils.d(e.toString());
                    }
                }
                processFinalHandle.finalHandle();
            }
        }.start();
    }

    /**
     * 关闭进度对话框
     */
    public void closeProgressDialog() {
//        LogUtils.d("ProgressDialog close");
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }







    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        noTitle();
        // 锁定屏幕为横向显示
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        requestWindowFeature(Window.FEATURE_ACTION_MODE_OVERLAY);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        ActionBar actionbar = getSupportActionBar();
        if (actionbar != null) {
            actionbar.hide();
        }
        getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //2.  加载界面
        setContentView(getLayoutID());
        initView();
        initData(savedInstanceState);
        initListener();
    }


    /**
     * 统一管理界面的跳转
     *
     * @param context context 的 对象
     * @param clazz   要跳转的 Activiity
     */
    protected void startActivity(Context context, Class<?> clazz) {
        Intent intent = new Intent(context, clazz);
        startActivity(intent);
    }


    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    public static boolean isForegroundActvity(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
//        boolean flag=false;
        for (ActivityManager.RunningTaskInfo taskInfo : list) {
            if (taskInfo.topActivity.getShortClassName().contains(className)) { // 说明它已经启动了
//                flag = true;
                return true;
            }
        }
        return false;
    }


    /**
     * 判定是否需要隐藏
     */
    private boolean isHideInput(View v, MotionEvent ev) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            if (ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 隐藏软键盘
     */
    private void HideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 按钮的点击操作
     */
    protected void initListener() {

    }

    /**
     * 初始化数据的方法，可以对数据进行操作
     *
     * @param savedInstanceState 保存的 Bundle
     */
    protected abstract void initData(Bundle savedInstanceState);

    /**
     * 加载控件，可以在里面做加载控件的操作
     */
    protected void initView() {

    }

    /**
     * 加载界面
     */

    protected abstract int getLayoutID();



    /**
     * 确认所有的权限是否都已授权
     *
     * @param grantResults
     * @return
     */
    public boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检测所有的权限是否都已授权
     *
     * @param permissions
     * @return
     */
    public boolean checkPermissions(String[] permissions) {
        if (Build.VERSION.SDK_INT < 23) {
            return true;
        }
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }


}
